<script setup>
import { ref, defineProps, watch } from 'vue'
import { VueFlow } from '@vue-flow/core'
import { useLayout } from '@/assets/js/useLayout'
import SpecialEdge from './SpecialEdge.vue'
import SpecialNode from './SpecialNode.vue'
import { defineEmits } from 'vue'
const emit = defineEmits(['currentNodeInfo', 'currentEdgeInfo'])
const props = defineProps(["data"])

let nodes = ref([])
let edges = ref([])
const { layout } = useLayout()

// 添加悬停状态管理
const hoveredNode = ref('')
const hoveredEdge = ref('')
const tooltipPosition = ref({ x: 0, y: 0 })

async function layoutGraph() {
    nodes.value = layout(nodes.value, edges.value, 'UD')
}

function generateNodesAndEdges(dataflows) {
    nodes.value = []
    edges.value = []

    let tNodes = []
    dataflows.forEach((dataflow) => {
        tNodes[dataflow.id] = dataflow.name
    })
    dataflows.forEach((dataflow) => {
        const node = {
            id: `${dataflow.id}`,
            type: 'dataflow',
            position: { x: 0, y: 0 },
            data: {
                label: dataflow.name,
                details: {
                    id: dataflow.id,
                    name: dataflow.name,
                    description: dataflow.description || '无描述',
                    type: dataflow.type || '未知类型',
                }
            },
        };
        nodes.value.push(node);
        dataflow["jump-list"].forEach((jump) => {
            addEdge(dataflow.id, jump.id, jump.condition, dataflow.name, tNodes[jump.id])
        });
    });
    layoutGraph()
}

function addEdge(source, target, cond, sourceName, targetName) {
    let hasIedge = -1
    edges.value.forEach((edge, index) => {
        if ((edge.source == target) && (edge.target == source)) {
            hasIedge = index
        }
    })
    if (hasIedge == -1) {
        edges.value.push({
            id: `${source}->${target}`,
            source: `${source}`,
            target: `${target}`,
            type: 'special',
            data: {
                left: cond,
                details: {
                    source: source,
                    target: target,
                    sourceName: sourceName,  // 存储源节点名称
                    targetName: targetName,  // 存储目标节点名称
                    condition: cond,
                    bidirectional: false
                }
            }
        });
    }
    else {
        edges.value[hasIedge].data.right = cond
        // 更新双向边的信息，添加反向名称
        edges.value[hasIedge].data.details = {
            ...edges.value[hasIedge].data.details,
            condition: `${cond} / ${edges.value[hasIedge].data.left}`,
            bidirectional: true
        }
    }
}


// 处理节点悬停事件
function handleNodeMouseEnter(event) {
    console.log(event)
    hoveredNode.value = event.node.data.details.description
    hoveredEdge.value = ''
    tooltipPosition.value = { x: event.event.clientX, y: event.event.clientY }
}

// 处理边悬停事件
function handleEdgeMouseEnter(event) {
    hoveredEdge.value = event.edge.data
    console.log(hoveredEdge.value)
    hoveredNode.value = ''
    tooltipPosition.value = { x: event.event.clientX, y: event.event.clientY }
}

// 清除悬停状态
function clearHover() {
    hoveredNode.value = ''
    hoveredEdge.value = ''
}
function handleClickNode(event) {
    let nodeInfo = {
        id: -1,
        name: '',
        description: '',
    }
    nodeInfo.id = event.node.data.details.id
    nodeInfo.name = event.node.data.details.name
    nodeInfo.description = event.node.data.details.description
    emit("currentNodeInfo", nodeInfo)
}
function handleClickEdge(event) {
    let edgeInfo = {
        source: '',
        sourceName: '',
        target: '',
        targetName: '',
        left: '',
        right: '',

    }
    edgeInfo.source = event.edge.data.details.source
    edgeInfo.sourceName = event.edge.data.details.sourceName
    edgeInfo.target = event.edge.data.details.target
    edgeInfo.targetName = event.edge.data.details.targetName
    edgeInfo.right = event.edge.data.right
    edgeInfo.left = event.edge.data.left
    emit("currentEdgeInfo", edgeInfo)
}

generateNodesAndEdges(props.data.workflow.dataflows)
watch(() => props.data.workflow.dataflows, (newDataflows) => {
    generateNodesAndEdges(newDataflows)
}, { immediate: true, deep: true })
</script>

<template>
    <!-- <div class="flow-container"> -->
    <VueFlow :nodes="nodes" :edges="edges" style="width: 100%;height: 100%;" @nodes-initialized="layoutGraph()"
        @node-mouse-enter="handleNodeMouseEnter" @node-mouse-leave="clearHover" @edge-mouse-enter="handleEdgeMouseEnter"
        @edge-mouse-leave="clearHover" @node-click="handleClickNode" @edge-click="handleClickEdge">
        <template #node-special="specialNodeProps">
            <SpecialNode v-bind="specialNodeProps" />
        </template>
        <template #edge-special="specialEdgeProps">
            <SpecialEdge v-bind="specialEdgeProps" />
        </template>
    </VueFlow>

    <!-- 节点详细信息弹窗 -->
    <div v-if="hoveredNode != ''" class="tooltip"
        :style="{ left: tooltipPosition.x + 'px', top: tooltipPosition.y + 'px' }">
        <div class="tooltip-header">节点详情</div>
        <div class="tooltip-content">
            <p>{{ hoveredNode }}</p>
        </div>
    </div>

    <!-- 边详细信息弹窗 -->
    <div v-if="hoveredEdge != ''" class="tooltip"
        :style="{ left: tooltipPosition.x + 'px', top: tooltipPosition.y + 'px' }">
        <div v-if="hoveredEdge.details.bidirectional == false">
            <div class="tooltip-header">单向边</div>
            <div class="tooltip-content">
                <!-- 显示节点名称 -->

                <p><strong>方向:</strong> {{ hoveredEdge.details.sourceName }} → {{
                    hoveredEdge.details.targetName }}
                </p>
                <p><strong>条件：</strong>{{ hoveredEdge.left }}</p>
            </div>
        </div>
        <div v-else>
            <div class="tooltip-header">双向边</div>
            <div class="tooltip-content">
                <!-- 正向边显示源节点和目标节点名称 -->
                <p><strong>方向:</strong> {{ hoveredEdge.details.sourceName }} → {{
                    hoveredEdge.details.targetName }}
                </p>
                <p><strong>条件：</strong>{{ hoveredEdge.left }}</p>
            </div>
            <div class="tooltip-content">
                <!-- 反向边显示目标节点和源节点名称 -->
                <p><strong>方向:</strong> {{ hoveredEdge.details.targetName }} → {{
                    hoveredEdge.details.sourceName }}
                </p>
                <p><strong>条件：</strong>{{ hoveredEdge.right }}</p>
            </div>
        </div>
    </div>

    <!-- </div> -->
</template>

<style>
@import '@vue-flow/core/dist/style.css';
@import '@vue-flow/core/dist/theme-default.css';

.flow-container {
    position: relative;
    width: 100%;
    height: 100%;
}

.tooltip {
    position: fixed;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 100;
    max-width: 300px;
    pointer-events: none;
    transform: translate(10px, 10px);
}

.tooltip-header {
    font-weight: bold;
    margin-bottom: 8px;
    padding-bottom: 4px;
    border-bottom: 1px solid #eee;
}

.tooltip-content p {
    margin: 5px 0;
    line-height: 1.4;
}
</style>